import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Container,
  Typography,
  Paper,
  Box,
  Grid,
  Card,
  CardContent,
  Button,
  Chip,
  CircularProgress,
  Alert,
  LinearProgress,
  IconButton,
  Menu,
  MenuItem,
} from '@mui/material';
import {
  Settings,
  ExitToApp,
  Person,
  Casino,
  MonetizationOn,
} from '@mui/icons-material';
import { styled } from '@mui/material/styles';

// Import components
import GameTable from '../components/game/GameTable';
import PlayerArea from '../components/game/PlayerArea';
import GameControls from '../components/game/GameControls';
import GameChat from '../components/game/GameChat';
import GameHistory from '../components/game/GameHistory';
import PlayerStats from '../components/game/PlayerStats';

// Import services and hooks
import gameService from '../services/gameService';
import { useAppSelector, useAppDispatch } from '../store/store';
import { setCurrentGame, clearError, GamePhase, GameState } from '../store/gameSlice';

// Styled components
const GameContainer = styled(Container)(({ theme }) => ({
  paddingTop: theme.spacing(2),
  paddingBottom: theme.spacing(2),
  minHeight: '100vh',
  backgroundColor: theme.palette.background.default,
}));

const GamePaper = styled(Paper)(({ theme }) => ({
  padding: theme.spacing(2),
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
}));

const TableContainer = styled(Box)(({ theme }) => ({
  position: 'relative',
  minHeight: 400,
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
}));

const PlayerPosition = styled(Box)<{ playerPosition: string }>(({ theme, playerPosition }) => {
  // Define positions for players around the table
  const positions: Record<string, any> = {
    'bottom': {
      position: 'absolute',
      bottom: 10,
      left: '50%',
      transform: 'translateX(-50%)',
    },
    'bottom-left': {
      position: 'absolute',
      bottom: 80,
      left: 80,
    },
    'left': {
      position: 'absolute',
      left: 10,
      top: '50%',
      transform: 'translateY(-50%)',
    },
    'top-left': {
      position: 'absolute',
      top: 80,
      left: 80,
    },
    'top': {
      position: 'absolute',
      top: 10,
      left: '50%',
      transform: 'translateX(-50%)',
    },
    'top-right': {
      position: 'absolute',
      top: 80,
      right: 80,
    },
    'right': {
      position: 'absolute',
      right: 10,
      top: '50%',
      transform: 'translateY(-50%)',
    },
    'bottom-right': {
      position: 'absolute',
      bottom: 80,
      right: 80,
    },
  };

  return positions[playerPosition] || {};
});

// Mock data for development
// Mock game state for development
const mockGameState: GameState = {
  id: 'game-123',
  name: 'Texas Hold\'em Table',
  players: [
    {
      id: 'player-1',
      username: 'You',
      chips: 1000,
      cards: [
        { value: 14, suit: 'hearts' },
        { value: 13, suit: 'spades' }
      ],
      currentBet: 0,
      hasFolded: false,
      isAllIn: false,
      position: 0
    },
    {
      id: 'player-2',
      username: 'Alice',
      chips: 1200,
      cards: [],
      currentBet: 10,
      hasFolded: false,
      isAllIn: false,
      position: 1
    },
    {
      id: 'player-3',
      username: 'Bob',
      chips: 800,
      cards: [],
      currentBet: 20,
      hasFolded: false,
      isAllIn: false,
      position: 2
    },
    {
      id: 'player-4',
      username: 'Charlie',
      chips: 1500,
      cards: [],
      currentBet: 0,
      hasFolded: true,
      isAllIn: false,
      position: 3
    }
  ],
  communityCards: [],
  pot: 30,
  currentBet: 20,
  dealerPosition: 1,
  currentPlayerPosition: 0,
  phase: GamePhase.WAITING,
  isStarted: true,
  minBet: 10,
  maxPlayers: 4
};

// Mock actions for game history
const mockActions = [
  { playerId: 'player-2', type: 'bet', amount: 10, timestamp: new Date() },
  { playerId: 'player-3', type: 'raise', amount: 20, timestamp: new Date() },
  { playerId: 'player-4', type: 'fold', amount: 0, timestamp: new Date() }
];

// 房间类型配置
const roomTypes = {
  beginner: {
    name: '新手房',
    minBuyIn: 100,
    maxBuyIn: 1000,
    smallBlind: 5,
    bigBlind: 10,
    minBet: 10
  },
  intermediate: {
    name: '中级房',
    minBuyIn: 500,
    maxBuyIn: 5000,
    smallBlind: 10,
    bigBlind: 20,
    minBet: 20
  },
  advanced: {
    name: '高级房',
    minBuyIn: 1000,
    maxBuyIn: 10000,
    smallBlind: 25,
    bigBlind: 50,
    minBet: 50
  }
};

// 根据当前下注额确定房间类型
const getRoomTypeByCurrentBet = (currentBet: number): keyof typeof roomTypes => {
  if (currentBet <= 100) return 'beginner';
  if (currentBet <= 500) return 'intermediate';
  return 'advanced';
};

// Convert numeric position to string position
const getPositionString = (pos: number): 'top' | 'left' | 'right' | 'bottom' => {
  switch(pos) {
    case 0: return 'bottom';
    case 1: return 'left';
    case 2: return 'top';
    case 3: return 'right';
    default: return 'bottom';
  }
};

const GameTablePage: React.FC = () => {
  const { gameId } = useParams<{ gameId: string }>();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  
  // Local state
  const [gameState, setGameState] = useState(mockGameState);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [settingsAnchorEl, setSettingsAnchorEl] = useState<null | HTMLElement>(null);
  
  // Redux state
  const { isLoading, error: reduxError } = useAppSelector(state => state.game);

  // 根据当前下注额确定房间类型和配置
  const currentRoomType = getRoomTypeByCurrentBet(gameState.currentBet);
  const roomConfig = roomTypes[currentRoomType];

  // Fetch game state on component mount
  useEffect(() => {
    const fetchGameState = async () => {
      if (!gameId) return;
      
      try {
        setLoading(true);
        setError(null);
        
        // Try to fetch actual game state
        const data = await gameService.getGameState(gameId);
        setGameState(data);
        dispatch(setCurrentGame(data));
      } catch (err) {
        console.error('Failed to fetch game state:', err);
        // Use mock data for now
        setGameState(mockGameState);
        dispatch(setCurrentGame(mockGameState));
      } finally {
        setLoading(false);
      }
    };

    fetchGameState();
  }, [gameId, dispatch]);

  // Handle menu
  const handleSettingsMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setSettingsAnchorEl(event.currentTarget);
  };

  const handleSettingsMenuClose = () => {
    setSettingsAnchorEl(null);
  };

  // Handle leave game
  const handleLeaveGame = () => {
    navigate('/lobby');
  };

  // Get current player
  const currentPlayer = gameState.players.find((p: any) => p.id === 'player-1');
  
  // Get current player position from game state
  const currentPlayerPosition = gameState.currentPlayerPosition || 0;
  
  // Determine if player can perform actions
  const canCheck = currentPlayer?.position === currentPlayerPosition && gameState.currentBet === (currentPlayer?.currentBet || 0);
  const canCall = currentPlayer?.position === currentPlayerPosition && gameState.currentBet > (currentPlayer?.currentBet || 0);
  const canRaise = currentPlayer?.position === currentPlayerPosition && (currentPlayer?.chips || 0) > gameState.currentBet;
  const canFold = currentPlayer?.position === currentPlayerPosition && !currentPlayer?.hasFolded;
  const canAllIn = currentPlayer?.position === currentPlayerPosition && (currentPlayer?.chips || 0) > 0;

  if (loading) {
    return (
      <GameContainer maxWidth="xl">
        <Box display="flex" justifyContent="center" alignItems="center" height="80vh">
          <CircularProgress />
        </Box>
      </GameContainer>
    );
  }

  return (
    <GameContainer maxWidth="xl">
      <Box mb={2} display="flex" justifyContent="space-between" alignItems="center">
        <Typography variant="h4" component="h1">
          {roomConfig.name} - 牌局 #{gameId?.slice(-6)}
        </Typography>
        
        <Box display="flex" alignItems="center">
          <Chip 
            label={`最小下注: $${roomConfig.minBet}`} 
            color="primary" 
            variant="outlined" 
            size="small" 
            sx={{ mr: 1 }} 
          />
          <Chip 
            label={`大盲注: $${roomConfig.bigBlind}`} 
            color="secondary" 
            variant="outlined" 
            size="small" 
            sx={{ mr: 2 }} 
          />
          
          <IconButton
            color="inherit"
            onClick={handleSettingsMenuOpen}
          >
            <Settings />
          </IconButton>
          
          <Menu
            anchorEl={settingsAnchorEl}
            open={Boolean(settingsAnchorEl)}
            onClose={handleSettingsMenuClose}
          >
            <MenuItem onClick={handleLeaveGame}>
              <ExitToApp sx={{ mr: 1 }} />
              离开游戏
            </MenuItem>
          </Menu>
        </Box>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      <Grid container spacing={2}>
        {/* Main game area */}
        <Grid size={{ xs: 12, md: 8 }}>
          <GamePaper>
            <Box mb={2} display="flex" justifyContent="space-between" alignItems="center">
              <Typography variant="h6">游戏桌面</Typography>
              <Box display="flex" alignItems="center">
                <MonetizationOn sx={{ mr: 0.5 }} color="primary" />
                <Typography variant="h6" color="primary">
                  底池: ${gameState.pot}
                </Typography>
              </Box>
            </Box>

            {isLoading && <LinearProgress sx={{ mb: 2 }} />}

            <TableContainer>
              <GameTable
                pot={gameState.pot}
                communityCards={gameState.communityCards}
                currentBet={gameState.currentBet}
                gamePhase={gameState.phase}
                minBet={roomConfig.minBet}
                bigBlind={roomConfig.bigBlind}
              />
              
              {/* Render players at their positions */}
              {gameState.players.map((player: any) => {
                // Get current player position from game state
                const currentPlayerPosition = gameState.currentPlayerPosition || 0;
                
                return (
                  <PlayerPosition key={player.id} playerPosition={getPositionString(player.position)}>
                    <PlayerArea
                      player={player}
                      isCurrentPlayer={player.id === 'player-1'}
                      isDealer={player.position === gameState.dealerPosition}
                      isTurn={player.position === currentPlayerPosition}
                      gamePhase={gameState.phase}
                      showCards={player.id === 'player-1'}
                      position={getPositionString(player.position)}
                    />
                  </PlayerPosition>
                );
              })}
            </TableContainer>
          </GamePaper>
        </Grid>

        {/* Side panels */}
        <Grid size={{ xs: 12, md: 4 }}>
          <Grid container spacing={2}>
            {/* Player stats */}
            <Grid size={{ xs: 12 }}>
              <GamePaper>
                <Typography variant="h6" gutterBottom>
                  玩家统计
                </Typography>
                {currentPlayer && (
                  <PlayerStats player={currentPlayer} />
                )}
              </GamePaper>
            </Grid>

            {/* Game controls */}
            <Grid size={{ xs: 12 }}>
              <GameControls
                gameId={gameId || ''}
                currentBet={gameState.currentBet}
                playerChips={currentPlayer?.chips || 0}
                canCheck={canCheck}
                canCall={canCall}
                canRaise={canRaise}
                canFold={canFold}
                canAllIn={canAllIn}
                minBet={roomConfig.minBet}
                bigBlind={roomConfig.bigBlind}
              />
            </Grid>

            {/* Game history */}
            <Grid size={{ xs: 12 }}>
              <GamePaper>
                <Typography variant="h6" gutterBottom>
                  游戏历史
                </Typography>
                <GameHistory actions={mockActions} />
              </GamePaper>
            </Grid>
          </Grid>
        </Grid>

        {/* Chat panel */}
        <Grid size={{ xs: 12, md: 4 }}>
          <GamePaper>
            <Typography variant="h6" gutterBottom>
              游戏聊天
            </Typography>
            <GameChat gameId={gameId || ''} />
          </GamePaper>
        </Grid>
      </Grid>
    </GameContainer>
  );
};

export default GameTablePage;